<?php

!defined('SYSTEM_INCLUDED') && exit('Access Denied');

Class App{
	
	public function __Construct(){
		
	}
	
	//app运行指令
	public function run(){
		$controller=$this->getController();
		$action=$this->getAction();
		//throw new CommonException ("controller is {$controller},action is {$action},debug is ok");
		//创建控制类实例
		$controllerInstance = $this->createController($controller);
		//控制器运行方法
		if(method_exists($controllerInstance,$action)){
			$controllerInstance->$action();
		}else{
			throw new CommonException ("Action is not found!");
		}
	}
	
	
	//取得controller名称
	public function getController(){
		if(defined('DEFAULT_CONTROLLER')){
			Config::change('DEFAULT_CONTROLLER',DEFAULT_CONTROLLER);
			return DEFAULT_CONTROLLER;
		}else{
			$controller_var=Config::get('CONTROLLER_VAR');
			$controller = !empty($_POST[$controller_var]) ? $_POST[$controller_var]
			: (!empty($_GET[$controller_var])? $_GET[$controller_var]: Config::get('DEFAULT_CONTROLLER'));
			//unset($_POST[$controller_var],$_GET[$controller_var]);
			//验证输入字串的合法性
			//SysBase::import('System.Validators.NumberAndLetterValidator');
			//SysBase::getInstance('NumberAndLetterValidator')->validate($controller);
			//Config::change('DEFAULT_CONTROLLER',$controller);
			return $controller;
		}
	}
	
	//取得action名称
	public function getAction(){
		if(defined('DEFAULT_ACTION')){
			Config::change('DEFAULT_ACTION',DEFAULT_ACTION);
			return DEFAULT_ACTION;
		}else{
			$action_var=Config::get('ACTION_VAR');
			$action = !empty($_POST[$action_var]) ? $_POST[$action_var]
			: (!empty($_GET[$action_var])? $_GET[$action_var]: Config::get('DEFAULT_ACTION'));
			//unset($_POST[$action_var],$_GET[$action_var]);
			Config::change('DEFAULT_ACTION',$action);
			return $action;
		}
	}
	
	//创建控制类实例
	function createController($controller){
		$controller = $controller.'Controller';
		$controllerFile = APP_PATH."/Controller/{$controller}.class.php";
		if(!is_file($controllerFile)){
			throw new CommonException ("Controller File is not found!");
		}
		require ($controllerFile);
		return SysBase::getInstance($controller);
	}
	
}